﻿Namespace SetupDatastore
    Friend Class FGetDatastorePathAndPassword
        Friend Result As Result

        Public Shared Function CreateAndShowDialog(ByVal owner As IWin32Window, ByVal defaultPath As String, ByVal defaultPwd As String) As Result
            Dim clsView As New FGetDatastorePathAndPassword
            clsView.Icon = CommonResources.My.Resources.Buddy
            clsView.txtPath.Text = defaultPath
            clsView.txtPassword.Text = defaultPwd
            clsView.ShowDialog(owner)
            Return clsView.Result
        End Function


        Private Sub txtPath_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPath.TextChanged
            If IO.File.Exists(txtPath.Text) Then
                btnOK.Text = "&Connect"
            Else
                btnOK.Text = "&Create"
            End If
        End Sub

        Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
            If IO.File.Exists(txtPath.Text) Then
                If Not DataStore.Environment.TestConnection(txtPath.Text, txtPassword.Text) Then
                    Select Case MessageBox.Show("Could not connect to the existing database! Continue and recreate?", "Connect", MessageBoxButtons.YesNo)
                        Case Windows.Forms.DialogResult.Yes
                        Case Else
                            txtPath.Focus()
                            Return
                    End Select
                End If
            End If

            Result = New Result
            Result.Path = txtPath.Text
            Result.Password = txtPassword.Text
            Me.Close()
        End Sub

        Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
            Result = Nothing
            Me.Close()
        End Sub

        Private Sub txtPath_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtPath.Validating
            txtPath.Text = txtPath.Text.Trim()
            If IO.Directory.Exists(txtPath.Text) Then
                txtPath.Text = IO.Path.Combine(txtPath.Text, "B2B.sdf")
            Else
                If Not txtPath.Text.ToUpper.EndsWith(".SDF") Then
                    txtPath.Text = txtPath.Text & ".sdf"
                End If
            End If
        End Sub
    End Class
End Namespace